package com.example.demo.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.BaseHttpParamPool;
import com.example.demo.util.IPUtils;
import com.example.demo.util.RequestDto;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

public class ParameterInterceptor extends HandlerInterceptorAdapter {
    /**
     * 在方法被调用前执行。在该方法中可以做类似校验的功能。如果返回true，则继续调用下一个拦截器。
     * 如果返回false，则中断执行，也就是说我们想调用的方法 不会被执行，但是你可以修改response为你想要的响应
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String id = String.valueOf(System.currentTimeMillis());
        System.out.println(id + "--接口请求开始："+ request.getRequestURI());

        String ip = IPUtils.getRealIP(request);//获取IP
        if (!"192.168.0.34".equals(ip)) {
            response.getWriter().write(JSONObject.toJSONString("非法请求,非法的IP:"));
            return  false;
        }


        StringBuilder sb = null;
        try (InputStream is = request.getInputStream()) {
            sb = new StringBuilder();
            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
        }

        // 读取到的参数字符串转成实体类
        RequestDto req = JSONObject.toJavaObject(JSONObject.parseObject(sb.toString()), RequestDto.class);
        Long inTime = req.getTimestamp();
        String sysCode = req.getPartner();
        String mesgId = req.getMesgId();
        String md5key = "abdcaaageff";  //作为MD5加密的字符串

        String sign = DigestUtils.md5Hex(sysCode + req.getContent() + req.getKey() + req.getTimestamp() + md5key);
        if(!sign.equals(req.getSign())) {
            response.getWriter().write(JSONObject.toJSONString("非法请求,无效的数据签名"));
            return false;
        }

        BaseHttpParamPool.setHttpServletRequest(req);
        BaseHttpParamPool.setHttpServletResponse(response);
        BaseHttpParamPool.setId(id);

        return super.preHandle(request, response, handler);
    }

    /**
     * 在业务处理器处理请求执行完成后，生成视图之前执行。后处理（调用了Service并返回ModelAndView，但未进行页面渲染），有机会修改ModelAndView；
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 在DispatcherServlet完全处理完请求后被调用，可用于清理资源等。返回处理（已经渲染了页面），
     * 可以根据ex是否为null判断是否发生了异常，进行日志记录；
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(BaseHttpParamPool.getId() + "--接口请求结束："+ request.getRequestURI());
        //记录 HttpServletRequest 和 HttpServletResponse
        BaseHttpParamPool.removeHttpServletRequest();
        BaseHttpParamPool.removeHttpServletResponse();
        BaseHttpParamPool.removeId();
        super.afterCompletion(request, response, handler, ex);
    }
}
